package cn.hlife.com.hlfhaemocyte;

import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.greendaodemo.greendao.gen.DaoMaster;
import com.greendaodemo.greendao.gen.DaoSession;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import cn.hlife.com.bluetooth20_connect.lib.BluetoothService;
import cn.hlife.com.hlfhaemocyte.bean.MeasureEntity;
import cn.hlife.com.hlfhaemocyte.bluetooth.BluetoothPrint;
import cn.hlife.com.hlfhaemocyte.bluetooth.ClientManager;
import cn.hlife.com.hlfhaemocyte.maintain.view.MaintainFragment;
import cn.hlife.com.hlfhaemocyte.measure.FragmentLinstener;
import cn.hlife.com.hlfhaemocyte.measure.MersurePrecentor;
import cn.hlife.com.hlfhaemocyte.measure.view.MeasureFragment;
import cn.hlife.com.hlfhaemocyte.measure.view.MeasureRecordActivity;
import cn.hlife.com.hlfhaemocyte.measure.view.MeasureRecordDetailsActivity;
import cn.hlife.com.hlfhaemocyte.notify.Transporter;
import cn.hlife.com.hlfhaemocyte.systemsetting.view.SettingFragment;
import cn.hlife.com.hlfhaemocyte.utils.DateUtil;
import cn.hlife.com.hlfhaemocyte.utils.DialogUtils;
import cn.hlife.com.hlfhaemocyte.utils.FragmentUtils;
import cn.hlife.com.hlfhaemocyte.utils.LogUtils;
import cn.hlife.com.hlfhaemocyte.utils.SharedPreferencesUtils;
import cn.hlife.com.hlfhaemocyte.utils.TransformDataUtils;
import cn.hlife.com.hlfhaemocyte.view.LoadingDialog;

import static com.inuker.bluetooth.library.Constants.REQUEST_FAILED;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;
import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;

public class MainActivity extends BaseActivity {

    private TabLayout tabLayout;
    public Fragment currentFragment;
    private final static UUID UUID_NOTIFY =
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
    private final static UUID UUID_SERVICE =
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
//    private String macAddress;
    Dialog loadindDialog;
    private StringBuffer stringBuffer;
    private MersurePrecentor mersurePrecentor;
    private DaoSession daoSession;
    private FragmentLinstener fragmentLinstener;
    public MeasureEntity measureEntity;
    public LoadingDialog meansureDialog;
    public int MEASURE_MODE;
    private OnBluetoothRecevier onBluetoothRecevier;
    AlertDialog alertDialog;
    ImageView indicatorLightG, indicatorLightR;
    Transporter transporter;
    public ImageView returnImageView;
    public TextView middleText, rightText;
    private BluetoothService mService = null;
    BluetoothDevice con_dev = null;
    /**
     * 创建一个Handler实例，用于接收BluetoothService类返回回来的消息
     */
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case BluetoothService.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED://已连接
                            com.utils.LogUtils.e("蓝牙打印机连接成功");
                            OutputStream stream = mService.getOutputStream();
                            if (stream != null) {
                                BluetoothPrint.getInstance().setOutputStream(stream);
                                indicatorLightR.setImageResource(R.drawable.d_green);
                                String macStr = readBluetoothMAC("macPrint");
                                transporter.notifyWatchers(macStr,true);

//                                AnimationDrawable animationDrawable = (AnimationDrawable) indicatorLightR.getDrawable();
//                                animationDrawable.start();
//                                try {
//                                    final Bitmap bitmap = BluetoothPrint.getInstance().createReportBitmap(measureEntity);
//                                    BluetoothPrint.getInstance().PrintBitmap(bitmap, mService);
//                                    final Bitmap bitmap2 = getViewBitmap(charGroup);
//                                    BluetoothPrint.getInstance().PrintBitmap(bitmap2, mService);
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
                            } else {
                                Toast.makeText(getApplicationContext(), "设备异常",
                                        Toast.LENGTH_SHORT).show();
                            }
                            break;
                        case BluetoothService.STATE_CONNECTING:  //正在连接
                            com.utils.LogUtils.e("蓝牙调试   正在连接.....");
                            break;
                        case BluetoothService.STATE_LISTEN:     //监听连接的到来
                        case BluetoothService.STATE_NONE:
                            com.utils.LogUtils.e("蓝牙调试  等待连接.....");
                            break;
                    }
                    break;
                case BluetoothService.MESSAGE_CONNECTION_LOST:    //蓝牙已断开连接
                    Toast.makeText(getApplicationContext(), "蓝牙打印机已断开",
                            Toast.LENGTH_SHORT).show();
                    String macStr = readBluetoothMAC("macPrint");
                    transporter.notifyWatchers(macStr,false);
                    indicatorLightR.setImageResource(R.drawable.d_gary);
//                    AnimationDrawable animationDrawable = (AnimationDrawable) indicatorLightR.getDrawable();
//                    animationDrawable.stop();
                    break;
                case BluetoothService.MESSAGE_UNABLE_CONNECT:     //无法连接设备
                    Toast.makeText(getApplicationContext(), "蓝牙打印机连接失败！",
                            Toast.LENGTH_SHORT).show();

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        indicatorLightG = (ImageView) findViewById(R.id.imageView1);
        indicatorLightR = (ImageView) findViewById(R.id.imageView2);
        returnImageView = (ImageView) findViewById(R.id.return_image);
        middleText = (TextView) findViewById(R.id.middle_text);
        rightText = (TextView) findViewById(R.id.left_text);
        tabLayout.addOnTabSelectedListener(onTabSelectedListener);
        currentFragment = FragmentUtils.switchFragment(getSupportFragmentManager(), R.id.fragment_content, currentFragment, MeasureFragment.class, null);
        measureEntity = new MeasureEntity();
        mersurePrecentor = new MersurePrecentor(this);
        mersurePrecentor.addMeasureListener(onMeansureListener);
        //创建dbmanager类初始化数据库
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this.getApplicationContext(), "user.db", null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        daoSession = daoMaster.newSession();
        stringBuffer = new StringBuffer();
        meansureDialog = new LoadingDialog(this);
//        macAddress = readBluetoothMAC("macBluetooth");
        switchConnectStatus();
        mService = new BluetoothService(this, handler);
        transporter=new Transporter();
        BluetoothPrint.getInstance().setBluetoothServiceInstance(mService);
        String macStr = readBluetoothMAC("macPrint");
        if(!TextUtils.isEmpty(macStr)){
            connBluetoothPair(macStr);
        }

//        findViewById(R.id.button5).setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                connBluetoothPair();
//            }
//        });
        LogUtils.e("初始化 ----");
    }

    /**
     * 读取蓝牙的MAC的地址
     */
    public String readBluetoothMAC(String key) {
        String macStr = SharedPreferencesUtils.getInstance().getBluetoothAddress(this);
        String macAddress = null;
        try {
            if (!TextUtils.isEmpty(macStr)) {
                JSONObject jsonObject = new JSONObject(macStr);
                macAddress = jsonObject.getString(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return macAddress;
    }

    public void switchConnectStatus() {
        if (!ClientManager.getClient().isBluetoothOpened()) {
            ClientManager.getClient().openBluetooth();
            Toast.makeText(this, "正在打开蓝牙", Toast.LENGTH_SHORT).show();
            ClientManager.getClient().registerBluetoothStateListener(mBluetoothStateListener);
            return;
        }
        String  macAddress = readBluetoothMAC("macBluetooth");
        int status = ClientManager.getClient().getConnectStatus(macAddress);
        if (TextUtils.isEmpty(macAddress)) {
            Toast.makeText(this, "请先填写mac地址", Toast.LENGTH_SHORT).show();
            return;
        }
        LogUtils.e("连接状态：" + status);
        switch (status) {
            case Constants.STATUS_UNKNOWN:
                break;
            case Constants.STATUS_DEVICE_CONNECTING:
                break;
            case Constants.STATUS_DEVICE_CONNECTED:
                Toast.makeText(this, "蓝牙已经连接", Toast.LENGTH_SHORT).show();
//                notifyMeth();

                break;
            case Constants.STATUS_DEVICE_DISCONNECTING:
                break;
            case Constants.STATUS_DEVICE_DISCONNECTED:
                connBle(macAddress);
                break;
        }
    }

    private final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {

        @Override
        public void onConnectStatusChanged(String mac, int status) {
            if (status == STATUS_CONNECTED) {
                transporter.notifyWatchers(mac,true);
//                ClientManager.getClient().notify(mac, UUID_SERVICE, UUID_NOTIFY, mNotifyRsp);
                indicatorLightG.setImageResource(R.drawable.d_green);
//                AnimationDrawable animationDrawable = (AnimationDrawable) indicatorLightG.getDrawable();
//                animationDrawable.start();

            } else if (status == STATUS_DISCONNECTED) {
                transporter.notifyWatchers(mac,false);
                Toast.makeText(MainActivity.this, "蓝牙连接断开", Toast.LENGTH_SHORT).show();
                indicatorLightG.setImageResource(R.drawable.d_gary);
//                AnimationDrawable animationDrawable = (AnimationDrawable) indicatorLightG.getDrawable();
//                animationDrawable.stop();
            }
        }
    };
    public Fragment getCurrnetFragment() {
        return currentFragment;
    }

    public void connBle(String  macAddress) {
        loadindDialog = new DialogUtils().createLoadingDialog(this, "蓝牙连接中...", new DialogUtils.OnProgressView() {
            @Override
            public void progressOnProgressView(ProgressBar progressBar) {
                progressBar.setVisibility(View.GONE);
            }
        });
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(3)   // 连接如果失败重试3次
                .setConnectTimeout(10000)   // 连接超时30s
                .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                .setServiceDiscoverTimeout(10000)  // 发现服务超时20s
                .build();
        ClientManager.getClient().registerConnectStatusListener(macAddress, mBleConnectStatusListener);
        ClientManager.getClient().connect(macAddress, options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile profile) {
                LogUtils.e("蓝牙连接返回结果：" + code);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        loadindDialog.dismiss();
                    }
                });
                if (code == REQUEST_SUCCESS) {
                    notifyMeth();
                    //TODO 修改
//                    writeCommand(new byte[]{(byte) 0xaa, 0x03, 0x09, 0x08, 0x01});
                } else if (code == REQUEST_FAILED) {
                    Toast.makeText(MainActivity.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            LogUtils.e("开启蓝牙返回值-->" + openOrClosed);
            if (openOrClosed) {
                switchConnectStatus();
            } else {
                Toast.makeText(MainActivity.this, "蓝牙已断开请检查蓝牙设备", Toast.LENGTH_SHORT).show();
            }
        }
    };

    public void notifyMeth() {
        String  macAddress = readBluetoothMAC("macBluetooth");

        ClientManager.getClient().notify(macAddress, UUID_SERVICE, UUID_NOTIFY, mNotifyRsp);
        ClientManager.getClient().registerConnectStatusListener(macAddress, mBleConnectStatusListener);
    }

    private final BleNotifyResponse mNotifyRsp = new BleNotifyResponse() {
        boolean isReceive = false;

        @Override
        public void onNotify(UUID service, UUID character, byte[] value) {
            if (service.equals(UUID_SERVICE) && character.equals(UUID_NOTIFY)) {
                String tem = TransformDataUtils.toHex(value);
                LogUtils.e("接收数据：" + tem);

                if (onBluetoothRecevier != null) {
                    onBluetoothRecevier.onResultRecever(value);
                    return;
                }
                if (isReceive) {
                    stringBuffer.append(tem);
                }
                if (stringBuffer.toString().contains("bb03050100")) {
                    LogUtils.e("测量结束-->>>");
//                    LogUtils.e("数据长度：" + stringBuffer.length());
                    isReceive = false;
                    String strBuf = stringBuffer.toString();
                    if (!TextUtils.isEmpty(strBuf)) {
                        mersurePrecentor.filtrateMeasureData(stringBuffer.toString(), MEASURE_MODE);
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                        }
                    });
                    stringBuffer.setLength(0);
                } else if (tem.equals("bb03050101")) {
                    LogUtils.e("测量开始-->>>");
                    isReceive = true;
                    stringBuffer.setLength(0);
                    stringBuffer.append(tem);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && !meansureDialog.isShowing()) {
                                meansureDialog.show();
                            }
                        }
                    });

                } else if (tem.equals("bb03052100")) {//全血模式返回的结果
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                        }
                    });
                } else if (tem.equals("bb03050400")) {//打稀释液模式返回的结果
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                        }
                    });
                } else if (tem.equals("bb03050900")//程序排堵 结束指令
                        || tem.equals("bb03050a00")//自动清洗 结束指令
                        || tem.equals("bb03050b00")//清空量杯 结束指令
                        || tem.contains("bb03050c00")//清空试剂 结束指令
                        || tem.equals("bb03050500")//灌注稀释液 结束指令
                        || tem.equals("bb03050200")//灌注溶血剂 结束指令
                        || tem.equals("bb03050300")//灌注清洁液 结束指令
                        || tem.startsWith("cc")
                        || tem.contains("bb03050800")) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                        }
                    });
                } else if (tem.equals("bb03050601")) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                            showDialog();
                        }
                    });
                } else if (tem.equals("bb03050602")) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (alertDialog != null && alertDialog.isShowing()) {
                                alertDialog.dismiss();
                            }
                            if (meansureDialog != null && !meansureDialog.isShowing()) {
                                meansureDialog.show();
                            }
                        }
                    });
                } else if (tem.equals("bb03050600")) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (alertDialog != null) {
                                alertDialog.show();
                            }
                        }
                    });
                } else if (tem.equals("bb03051401")) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (alertDialog != null && alertDialog.isShowing()) {
                                alertDialog.dismiss();
                            }
                            if (meansureDialog != null && !meansureDialog.isShowing()) {
                                meansureDialog.show();
                            }
                        }
                    });
                } else if (tem.equals("bb03051400")) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (meansureDialog != null && meansureDialog.isShowing()) {
                                meansureDialog.dismiss();
                            }
                        }
                    });
                }
            }
        }

        @Override
        public void onResponse(int code) {
            if (code == REQUEST_SUCCESS) {
            }
        }
    };

    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("系统提示");
        builder.setMessage("请将保养液放入探针");
        alertDialog = builder.create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    public MersurePrecentor.OnMeansureListener onMeansureListener = new MersurePrecentor.OnMeansureListener() {

        @Override
        public void finishMeasure() {
            if (measureEntity != null) {
                MeasureFragment measureFragment = (MeasureFragment) FragmentUtils.getFragmentInstance(getSupportFragmentManager(), MeasureFragment.class);
                measureEntity.setId(System.currentTimeMillis());
                measureEntity.setMUserName(measureFragment.getmUserName().getText().toString());
                measureEntity.setUserSex(measureFragment.getUserSex());
                measureEntity.setMAge(measureFragment.getmAge().getText().toString());
                measureEntity.setMSection(measureFragment.getmSection().getText().toString());
                measureEntity.setMMedicalNumber(measureFragment.getmMedicalNumber().getText().toString());
                measureEntity.setMHospitalBedNumber(measureFragment.getmHospitalBedNumber().getText().toString());
                measureEntity.setMSampleID(measureFragment.getmSampleID().getText().toString());
                measureEntity.setMSpecimen(measureFragment.getmSpecimen().getText().toString());
                measureEntity.setMDoctor(measureFragment.getmDoctor().getText().toString());
                measureEntity.setMTime(measureFragment.getmTime().getText().toString());
                measureEntity.setMClinicalDiagnosis(measureFragment.getmClinicalDiagnosis().getText().toString());
                measureEntity.setMRemark(measureFragment.getmRemark().getText().toString());
                measureEntity.setTempFY(mersurePrecentor.getTempFY());
                measureEntity.setRBCNumber(mersurePrecentor.getRBCNumber());
                measureEntity.setWBCNUmber(mersurePrecentor.getWBCNUmber());
                measureEntity.setPLTNumber(mersurePrecentor.caculatePLTNumber());
                measureEntity.setHGB_Value(mersurePrecentor.getHGB_Value());
                measureEntity.setHCT_Value(mersurePrecentor.getHCT_Value());
                measureEntity.setInspector("");
                measureEntity.setVerifyPerson("");
                measureEntity.setMCV_Value(mersurePrecentor.getMCV_Value());
                measureEntity.setMCH_Value(mersurePrecentor.getMCH_Value());
                measureEntity.setMCHC_Value(mersurePrecentor.getMCHC_Value());
                measureEntity.setLymNumber_Value(mersurePrecentor.getLymNumber_Value());
                measureEntity.setLymPercent_Value(mersurePrecentor.getLymPercent_Value());
                measureEntity.setMidNumber_Value(mersurePrecentor.getMidNumber_Value());
                measureEntity.setMidPercent_Value(mersurePrecentor.getMidPercent_Value());
                measureEntity.setNeuNumber_Value(mersurePrecentor.getNeuNumber_Value());
                measureEntity.setNeuPercent_Value(mersurePrecentor.getNeuPercent_Value());

                measureEntity.setRBCNumberSum(mersurePrecentor.getRBCNumberSum().toString());
                measureEntity.setWBCNumberSum(mersurePrecentor.getWBCNumberSum().toString());
                measureEntity.setPLTNumberSum(mersurePrecentor.getPLTNumberSum().toString());
                measureEntity.setMPV_Temp_Value(mersurePrecentor.getMPV_Temp_Value());
                measureEntity.setMCV_Temp_Value(mersurePrecentor.getMCV_Temp_Value());
                measureEntity.setMPV_Value(mersurePrecentor.getMPV_Value());
                measureEntity.setPCT_Value(mersurePrecentor.getPCT_Value());
                measureEntity.setMeasueDate(DateUtil.date2Str(new Date()));
                measureEntity.setRDWCV_Value(mersurePrecentor.getRDWCV_Value());
                measureEntity.setRDWSD_Value(mersurePrecentor.getRDWSD_Value());
                measureEntity.setPDW_Value(mersurePrecentor.getPDW_Value());
                measureEntity.setPLCR_Value(mersurePrecentor.getPLCR_Value());
                long id = daoSession.insert(measureEntity);
                Intent intent = new Intent(MainActivity.this, MeasureRecordDetailsActivity.class);
                intent.putExtra("_id", id);
                intent.putExtra("isEdit", true);
                startActivity(intent);
            }
        }
    };

    public interface OnBluetoothRecevier {

        public void onResultRecever(byte[] value);

    }

    public void setOnBluetoothInstance(OnBluetoothRecevier onBluetoothRecevier) {
        this.onBluetoothRecevier = onBluetoothRecevier;
    }

    public void writeCommand(byte[] command) {
        String  macAddress = readBluetoothMAC("macBluetooth");

        handler.post(new Runnable() {
            @Override
            public void run() {
                meansureDialog.show();
            }
        });
        ClientManager.getClient().write(macAddress, UUID_SERVICE, UUID_NOTIFY, command, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                    LogUtils.e("发送成功!");
                }
            }
        });
    }

    public void writeCommandNoDialog(byte[] command) {
        String  macAddress = readBluetoothMAC("macBluetooth");
        ClientManager.getClient().write(macAddress, UUID_SERVICE, UUID_NOTIFY, command, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                    LogUtils.e("发送成功!");
                }
            }
        });
    }

    public TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int position = tab.getPosition();
            switchFragment(position);

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {


        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {


        }
    };

    public void switchFragment(int position) {
        switch (position) {
            case 0:
                rightText.setVisibility(View.VISIBLE);
                middleText.setText("血细胞分析仪");
                rightText.setOnClickListener(onViewClick);
                rightText.setText("测量记录");
                returnImageView.setVisibility(View.GONE);
                currentFragment = FragmentUtils.switchFragment
                        (getSupportFragmentManager(), R.id.fragment_content, currentFragment, MeasureFragment.class, null);

                break;
            case 1:
                currentFragment = FragmentUtils.switchFragment
                        (getSupportFragmentManager(), R.id.fragment_content, currentFragment, MaintainFragment.class, null);

                break;
            case 2:
                currentFragment = FragmentUtils.switchFragment
                        (getSupportFragmentManager(), R.id.fragment_content, currentFragment, SettingFragment.class, null);

                break;
        }
    }
    public View.OnClickListener  onViewClick=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.left_text:
                    Intent intent = new Intent(MainActivity.this, MeasureRecordActivity.class);
                    startActivity(intent);
                    break;
            }
        }
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        mService.stop();
        String  macAddress = readBluetoothMAC("macBluetooth");
        ClientManager.getClient().disconnect(macAddress);
        ClientManager.getClient().unregisterBluetoothStateListener(mBluetoothStateListener);
        ClientManager.getClient().unregisterConnectStatusListener(macAddress, mBleConnectStatusListener);

    }

    public Transporter getTransporter() {
        return transporter;
    }

    public void connBluetoothPair(String  macStr) {
        if(mService.getState()==BluetoothService.STATE_NONE||mService.getState()==BluetoothService.STATE_LISTEN){
//            con_dev = mService.getDevByMac("00:BA:55:81:DB:A8");
            con_dev = mService.getDevByMac(macStr);
            if (con_dev != null) {
                mService.connect(con_dev);
            } else {
                Toast.makeText(getApplicationContext(), "没有找到该设备",
                        Toast.LENGTH_SHORT).show();
            }
        }else{
            LogUtils.e("蓝牙的状态："+mService.getState());
        }

    }
}
